<?php


namespace app\command;


use app\api\cache\KeysUtil;
use app\api\cache\RedisCache;
use app\api\consDir\CommunityConst;
use app\api\services\MemberService;
use app\common\models\Community\CommunityOrder;
use app\common\models\Community\CommunityUser;
use app\common\utils\CommonUtil;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class CommunityCancel extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('community:cancel')
            ->setDescription('社区订单取消');
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $output->info("开始:");
        $where = [
            ['status', '=', CommunityConst::ORDER_NO_PAY],
            ['expire_at', '<', date('Y-m-d H:i:s')],
            ['type','<>',3]
        ];
        $list = CommunityOrder::getInstance()->where($where)->select();
        if (empty($list)) {
            return;
        }
        foreach ($list as $val) {
            $communityOrder = CommunityOrder::getInstance()->where('id',$val['id'])->lock(true)->find();
            //1未支付订单
            if ($communityOrder['status'] != 1) {
                continue;
            }
            CommunityOrder::getInstance()->startTrans();
            try {
                //更新 订单取消
                $communityOrder->status = 3;
                $communityOrder->updateAt = date('Y-m-d H:i:s');
                $communityOrder->save();
                //更新社区
                $communityUser = CommunityUser::getInstance()->where('community_id', $val->community_id)->find();
                if ($communityUser && in_array($communityUser['communityStatus'], [CommunityConst::CAN_STATUS, CommunityConst::RELEASE_STATUS, CommunityConst::BUY_STATUS])) {
                    $communityUser->communityStatus = $communityUser['userId'] > 0 ? CommunityConst::RELEASE_STATUS : CommunityConst::CAN_STATUS;
                    //$communityUser->updateAt = date('Y-m-d H:i:s');
                    $communityUser->save();
                    RedisCache::hMSet(KeysUtil::getCommunityInfo($val['communityId']), CommonUtil::camelToUnderLine($communityUser->toArray()));
                }
                CommunityOrder::getInstance()->commit();
            } catch (\Exception $e) {
                CommunityOrder::getInstance()->rollback();
                $output->info("异常:" . $e->getMessage());
            }
        }
        $output->info("结束:");
    }

}